<template>
    <div class="mainBox">
        <el-card style="max-width: 70%;">
            <el-form :model="selfInfo" label-width="auto" style="max-width: 600px">
                <el-row :gutter="20">
                    <div>
                        <el-form-item label="头像">
                            <el-avatar :size="50" :src="selfInfo.headImage" /><el-col :span="3"></el-col>
                            <el-upload class="avatar-uploader" :beforeUpload="beforeImgUpload" :show-file-list="false"
                                :accept="'image/jpeg,image/jpg,image/png,.jpg,.png,.jpeg'">
                                <el-button v-show="ischangable" type="primary">修改头像</el-button>
                            </el-upload>
                        </el-form-item>
                    </div>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="姓名">
                        <el-input :disabled="!ischangable" v-model="selfInfo.userName" />
                    </el-form-item>
                </el-row>
                <el-form-item label="用户ID">
                    <el-text>{{ selfInfo.id }}</el-text>
                </el-form-item>
                <el-form-item label="账号/学号">
                    <el-text>{{ selfInfo.account }}</el-text>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group :disabled="!ischangable" v-model="selfInfo.sex">
                        <el-radio :value=0>男</el-radio>
                        <el-radio :value=1>女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="所在大学">
                    <el-text>{{ selfInfo.schName }}</el-text>
                </el-form-item>
                <div class="longInput">
                    <el-form-item label="邮箱">
                        <el-input :disabled="!ischangable" v-model="selfInfo.email" />
                    </el-form-item>
                </div>
                <div class="longInput">
                    <el-form-item label="联系方式">
                        <el-input class="longInput" :disabled="!ischangable" v-model="selfInfo.phoneNum" />
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-row :gutter="150">
                        <el-col :span="4"></el-col>

                        <el-button type="primary" v-show="!ischangable" @click="changable">修改个人信息</el-button>
                        <el-button type="primary" v-show="!ischangable" @click="changePassword">修改密码</el-button>

                    </el-row>
                    <el-row :gutter="150">
                        <el-col :span="4"></el-col>
                        <el-col :span="4">
                            <el-button type="primary" v-show="ischangable" @click="onSubmit">保存修改</el-button>
                        </el-col>
                        <el-col :span="2"><el-button type="info" v-show="ischangable"
                                @click="handleCancel">取消修改</el-button></el-col>
                    </el-row>

                </el-form-item>
            </el-form>
        </el-card>
    </div><!-- 修改密码对话框 -->
    <el-dialog v-model="passwordChangable" title="修改密码" width="500" center>
        <span>
            <el-row>
                <el-col :span="7">
                    请输入原密码：
                </el-col>
                <el-col :span="12">
                    <el-input v-model="passwords.oldPassword" type="password" show-password style="width: 240px" placeholder="原密码" />
                </el-col>
            </el-row>
            <br>
            <el-row>
                <el-col :span="7">
                    请输入新密码：
                </el-col>
                <el-col :span="12">
                    <el-input v-model="passwords.newPassword" type="password" show-password style="width: 240px" placeholder="新密码" />
                </el-col>
            </el-row>
            <br>
            <el-row>
                <el-col :span="7">
                    请再次输入新密码：
                </el-col>
                <el-col :span="12">
                    <el-input v-model="passwords.newPasswordSec" type="password" show-password style="width: 240px" placeholder="再次确认新密码" />
                </el-col>
            </el-row>
            <br><br>
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="makeSureChange">
                    确认修改
                </el-button>
                <el-button @click="passwordChangable = false">
                    取消操作
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import api from '@/api';
import { onMounted, reactive, ref } from 'vue';
import showMessageTip from '@/utils/showMessage';


const ischangable = ref(false)
const passwordChangable = ref(false)
const passwords = reactive({
    oldPassword:'',
    newPassword:'',
    newPasswordSec:''
})
const selfInfo = reactive({
    id: '',
    userName: '',
    account: '',
    sex: -1,
    schName: '',
    email: '',
    phoneNum: '',
    headImage: ''
})
const temp = reactive({  //用于储存临时修改的个人信息
    id: '',
    userName: '',
    account: '',
    sex: -1,
    schName: '',
    email: '',
    phoneNum: '',
    headImage: ''
})
const imgData = ref(null);


const changable = () => {
    Object.assign(temp, { ...selfInfo });
    ischangable.value = true;
}
const handleCancel = () => {
    ischangable.value = false;
    Object.assign(selfInfo, { ...temp });
}
const changePassword = () => {
    passwordChangable.value = true;

}
const makeSureChange= async() =>{
    if((passwords.oldPassword=='')||(passwords.newPassword=='')||passwords.newPasswordSec==''){
        showMessageTip('输入不能为空', 'warning');
        return;
    }
    if(passwords.newPassword!=passwords.newPasswordSec){
        showMessageTip('两次新密码不一致', 'warning');
        return;
    }
    const pass= reactive({
        password:passwords.oldPassword,
        newPassword: passwords.newPassword
    })
    const result = await api.changePassword(pass);
    if(result[0]==0){
        const data = result[1].data;
        if(data.code==1){
            showMessageTip('修改成功', 'success');
            passwordChangable.value=false;
             return;
        }
        if(data.msg=='old password error'){
            showMessageTip('原密码输入有误', 'error');
             return;
        }
        else if(data.msg=='easy password'){
            showMessageTip('密码过于简单', 'warning');
             return;
        }
    }
    else{
        showMessageTip('网络请求失败', 'error');
        return;
    }
}
const onSubmit = async () => {  //提交
    ischangable.value = false;
    const uploadData = reactive({});
    const imgUrl = ref('');
    if (selfInfo.userName != temp.userName) {
        uploadData.userName = selfInfo.userName;
    }
    if (selfInfo.sex != temp.sex) {
        uploadData.sex = selfInfo.sex;
    }
    if (selfInfo.email != temp.email) {
        uploadData.email = selfInfo.email;
    }
    if (selfInfo.phoneNum != temp.phoneNum) {
        uploadData.phoneNum = selfInfo.phoneNum;
    }
    if (imgData.value != null) {
        const formData = new FormData();
        formData.append('image', imgData.value);
        const imgResult = await api.uploadImage(formData);
        if (imgResult[0] == 0) {
            const data = imgResult[1].data;
            if (data.code == 0) {
                showMessageTip('图片上传失败,请重新尝试', 'error');
                return;
            }
            imgUrl.value = data.data;
        }
        else {
            showMessageTip('图片上传失败,请重新尝试', 'error');
            return;
        }
    }
    const dataResult = await api.updateSelfInfo(uploadData);
    Object.assign(selfInfo, { ...temp });
    if (dataResult[0] == 0) {
        const data = dataResult[1].data;
        if (data.code == 0) {
            showMessageTip('修改失败,请重新尝试', 'error');
            return;
        }
        Object.assign(selfInfo, { ...uploadData });
    }
    else {
        showMessageTip('修改失败,请重新尝试', 'error');
        return;
    }
    selfInfo.headImage = imgUrl.value + '?' + Date.now();
    showMessageTip('个人信息修改成功！', 'success');
}
onMounted( async () => {
    const result = await api.getSelfInfo();
    if(result[0] === 0){
        const data = result[1].data;       
        if(data.code == 0){
            showMessageTip('数据请求失败,请重新尝试','error');
            return;
        }
        Object.assign(selfInfo,{ ...data.data });
    }else{
        showMessageTip('数据请求失败,请重新尝试','error');
    }
});

const beforeImgUpload = async (file) => {
    if (!file.type.startsWith('image/')) {
        showMessageTip('不支持的文件格式', 'warning');
        return false;
    }
    else if (!(file.size / 1024 / 1024 < 2)) {
        showMessageTip('文件不能大于2M', 'warning')
        return false;
    }
    else {
        imgData.value = file;
        if (imgData.value != null) {
            selfInfo.headImage = await imgToUrl(imgData.value);
            showMessageTip('图片加载成功！', 'success');
        }
        return false;
    }
}
const imgToUrl = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
            resolve(event.target.result); // 返回Base64URL
        };
        reader.onerror = (error) => {
            reject(new Error('文件读取错误' + error));
        };
        reader.readAsDataURL(file);
    });
}
</script>

<style scoped>
.el-header {
    padding: 0;
}

.sideChoice {
    position: absolute;
    top: 74px;
}

.demo-type {
    display: flex;
}

.demo-type>div {
    flex: 1;
    text-align: center;
}

.demo-type>div:not(:last-child) {
    border-right: 1px solid var(--el-border-color);
}
.longInput {
    max-width: 450px;
}
</style>
